package com.example.shipload_e.activitys.exception_feedback;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.example.shipload_e.R;
import com.example.shipload_e.activitys.shipment_feedback.ShipmentFinishFormActivity.MyAdapter;
import com.example.shipload_e.activitys.shipment_feedback.ShipmentFinishFormActivity.ViewHolder;
import com.example.shipload_e.database_dao.BizDBAdapter;
import com.example.shipload_e.database_dao.ClassConvertBean;
import com.example.shipload_e.service.BizNetworkService;
import com.example.shipload_e.util.HttpActConstant;
import com.example.shipload_e.util.HttpConstant;
import com.example.shipload_e.util.SystemDateTools;

public class ExceptionFeedbackFormActivity extends Activity {
	private ImageButton	              mGoback;
	private EditText	              datePickerEt, timePickerEt, remarkEdit;
	private ImageButton	              submitBt;
	private Spinner	                  exceptionTypeSp;
	ProgressDialog	                  progressDialog;
	private MyHandler	              handlers;
	private String	                  submitData	= "00";
	private String	                  submitTime	= "00";
	private ListView	              recordList;
	private List<Map<String, Object>>	mData;
	private boolean	                  hasDatas	 = false;
	ExceptionFeedbackFormActivity	  THISAC	 = ExceptionFeedbackFormActivity.this;

	static class MyHandler extends Handler {
		WeakReference<ExceptionFeedbackFormActivity>	tActivity;

		MyHandler(ExceptionFeedbackFormActivity activity) {
			tActivity = new WeakReference<ExceptionFeedbackFormActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			ExceptionFeedbackFormActivity theActivity = tActivity.get();
			Bundle data = msg.getData();
			if(!data.isEmpty()) {
				switch (msg.what) {
					case HttpActConstant.SUBMIT_EXCEPTION_FEEDBACK_TASKS:
						theActivity.progressDialog.dismiss();
						if(HttpConstant.SUBMIT_SUCCESS.equals(data
						        .getString(HttpConstant.SUBMIT_SUCCESS))) {
							new Thread(new BizNetworkService(theActivity, new Handler(), HttpActConstant.INIT_EXCEPTION_FEEDBACK_TASKS, null))
							        .start();
							theActivity.progressDialog.setMessage("正在更新列表...");
							theActivity.progressDialog.show();
						}
						Toast.makeText(theActivity, data.getString("msg"), Toast.LENGTH_SHORT)
						        .show();
						break;

					default:
						break;
				}
			} else {}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.exception_feedback_edit_main);
		progressDialog = new ProgressDialog(THISAC);
		handlers = new MyHandler(THISAC);
		initDatas();
		initView();
		com.example.shipload_e.util.SysApplication.getInstance().addActivity(this);
	}

	private void initView() {
		mGoback = (ImageButton) findViewById(R.id.m_goback);
		mGoback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		remarkEdit = (EditText) findViewById(R.id.remark_edit);
		datePickerEt = (EditText) findViewById(R.id.date_picker);
		timePickerEt = (EditText) findViewById(R.id.time_picker);
		datePickerEt.setText(SystemDateTools.getDateByNowByType("yyyy年MM月dd日"));
		timePickerEt.setText(SystemDateTools.getDateByNowByType("HH时mm分"));
		datePickerEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0,boolean arg1) {
				if(arg1) {
					int year = Integer.parseInt(SystemDateTools.getYearFromDate());
					int month = Integer.parseInt(SystemDateTools.getMonthFromDate());
					int day = Integer.parseInt(SystemDateTools.getDayFromDate());
					DatePickerDialog datePickerLog = new DatePickerDialog(THISAC, new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view,int year,int monthOfYear,
						        int dayOfMonth) {
							// TODO Auto-generated method stub
							Toast.makeText(THISAC, year + "year " + (monthOfYear + 1) + "month "
							        + dayOfMonth + "day", Toast.LENGTH_SHORT).show();

							datePickerEt.setText(year + "年 " + (monthOfYear + 1) + "月 "
							        + dayOfMonth + "日");
							datePickerEt.clearFocus();
							submitData = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
						}
					}, year, month - 1, day);
					datePickerLog.show();
				}
			}
		});
		timePickerEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0,boolean arg1) {
				if(arg1) {
					int hous = Integer.parseInt(SystemDateTools.getSystemHourOfTime());
					int minute = Integer.parseInt(SystemDateTools.getSystemMinuteOfTime());
					TimePickerDialog time = new TimePickerDialog(THISAC, new OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker view,int hourOfDay,int minute) {
							// TODO Auto-generated method stub
							Toast.makeText(THISAC, hourOfDay + "hour " + minute + "minute", Toast.LENGTH_SHORT)
							        .show();
							timePickerEt.setText(hourOfDay + "时" + minute + "分");
							submitTime = hourOfDay + ":" + minute + ":00";
							timePickerEt.clearFocus();
						}
					}, hous, minute, true);
					time.show();
				}
			}
		});
		submitBt = (ImageButton) findViewById(R.id.ex_submit_button);
		submitBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				progressDialog.setMessage("正在提交...");
				progressDialog.show();
				HashMap<String, String> map = new HashMap<String, String>();
				String getFollowId = getIntent().hasExtra("followId") == false ? "isNone"
				        : getIntent().getStringExtra("followId");
				map.put("taskId", getFollowId);
				String tid = ((CItem) exceptionTypeSp.getSelectedItem()).getID().toString();
				map.put("type", tid);
				map.put("time", (submitData.equals("00") ? SystemDateTools.getDateByNow()
				        : submitData)
				        + " "
				        + (submitTime.equals("00") ? SystemDateTools.getTimeByNow() : submitTime));
				map.put("remarks", remarkEdit.getText().toString());
				new Thread(new BizNetworkService(THISAC, handlers, HttpActConstant.SUBMIT_EXCEPTION_FEEDBACK_TASKS, map))
				        .start();
			}
		});
		exceptionTypeSp = (Spinner) findViewById(R.id.exception_et);
		initSpinner();
	}

	private void initSpinner() {
		ArrayAdapter<CItem> adapter1;
		List<CItem> ls1 = new ArrayList<CItem>();
		String sql = "SELECT * FROM TYPES";
		BizDBAdapter db = new BizDBAdapter(THISAC);
		Cursor cs = db.openDBConnection().rawQuery(sql, new String[]{});
		JSONArray jdatas = ClassConvertBean.returnJsonBeans(cs);
		cs.close();
		db.close();
		if(jdatas.length() > 0) {
			for(int j = 0;j < jdatas.length();j++) {
				try {
					String id = jdatas.getJSONObject(j).getString("ID");
					String name = jdatas.getJSONObject(j).getString("NAME");
					CItem item = new CItem(id, name);
					ls1.add(item);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		} else {
			String id = "0";
			String name = "无";
			CItem item = new CItem(id, name);
			ls1.add(item);
		}
		adapter1 = new ArrayAdapter<CItem>(THISAC, android.R.layout.simple_spinner_item, ls1);
		adapter1.setDropDownViewResource(R.layout.drop_down_item);
		exceptionTypeSp.setAdapter(adapter1);
		exceptionTypeSp.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent,View view,int position,long id) {
				String tid = ((CItem) exceptionTypeSp.getSelectedItem()).getID().toString();
				System.out.println(tid);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	public class CItem {
		private String	ID		= "";
		private String	Value	= "";

		public CItem() {
			ID = "";
			Value = "";
		}

		public CItem(String _ID, String _Value) {
			ID = _ID;
			Value = _Value;
		}

		@Override
		public String toString() {
			return Value;
		}

		public String getID() {
			return ID;
		}

		public String getValue() {
			return Value;
		}
	}

	private void initDatas() {
		try {
			String result = getIntent().hasExtra("followResult") == false ? "isNone" : getIntent()
			        .getStringExtra("followResult");
			JSONArray getResult;
			getResult = new JSONArray(result.toString());
			System.out.println(getResult);
			getResult.getString(0);
			List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
			for(int i = 0;i < getResult.length();i++) {
				JSONObject o = new JSONObject(getResult.getString(i));
				if(o.has("records")) {
					String records = o.getString("records");
					JSONArray ja = new JSONArray(records.toString());
					int showListLenght = ja.length() > 5 ? 5 : ja.length();
					for(int j = 0;j < showListLenght;j++) {
						hasDatas = true;
						String MSG = ja.getJSONObject(j).has("MSG") == false ? "" : ja
						        .getJSONObject(j).getString("MSG");
						String TASKID = ja.getJSONObject(j).has("TASKID") == false ? "" : ja
						        .getJSONObject(j).getString("TASKID");
						String OPUSER = ja.getJSONObject(j).has("OPUSER") == false ? "" : ja
						        .getJSONObject(j).getString("OPUSER");
						String OPTIME = ja.getJSONObject(j).has("OPTIME") == false ? "" : ja
						        .getJSONObject(j).getString("OPTIME");
						String AURESULT = ja.getJSONObject(j).has("AURESULT") == false ? "" : ja
						        .getJSONObject(j).getString("AURESULT");
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("msg", MSG);
						map.put("taskId", TASKID);
						map.put("opUser", OPUSER);
						map.put("opTime", OPTIME);
						map.put("auResult", AURESULT);
						mapList.add(map);
					}
				}
			}

			if(hasDatas) {
				recordList = (ListView) findViewById(R.id.record_list);
				// 生成动态数组，并且转入数据
				mData = mapList;
				// 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
				MyAdapter adapter = new MyAdapter(this);
				recordList.setAdapter(adapter);

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public final class ViewHolder {
		public TextView		recordMsg, recordTime, recordMen;
		public LinearLayout	shipperItemLin;
	}

	public class MyAdapter extends BaseAdapter {

		private final LayoutInflater	mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@SuppressLint({"NewApi", "ResourceAsColor" })
		@Override
		public View getView(final int position,View convertView,ViewGroup parent) {

			ViewHolder holder = null;

			holder = new ViewHolder();

			convertView = mInflater.inflate(R.layout.record_saggese_list_item, null);
			holder.recordMsg = (TextView) convertView.findViewById(R.id.record_msg);
			holder.recordTime = (TextView) convertView.findViewById(R.id.record_time);
			holder.recordMen = (TextView) convertView.findViewById(R.id.record_men);
			holder.shipperItemLin = (LinearLayout) convertView.findViewById(R.id.shipper_item_lin);
			convertView.setTag(holder);
			if(position % 2 == 1) {
				holder.shipperItemLin.setBackgroundColor(getResources()
				        .getColor(R.color.list_item_color1));
			} else {
				holder.shipperItemLin.setBackgroundColor(getResources()
				        .getColor(R.color.list_item_color));
			}
			holder.recordMsg.setText(mData.get(position).get("msg").toString());
			holder.recordTime.setText(mData.get(position).get("opTime").toString());
			holder.recordMen.setText(mData.get(position).get("opUser").toString());
			return convertView;
		}
	}
}
